
package com.example;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * KbShrtcutReminder
 * DataManager.java
 * Purpose: Has access to the file where shortcuts has been stored and responds to requests of other objects related to shortcut
 *
 * @author Deranga Chamali
 * @version 1.1 23/12/2010
 */
public class DataManager {

    String relatedWords[][];
    String functionNames[] = new String[113];
    String shortcuts[] = new String[113];
    String homepath;////////////////////////////////////////////////////

    /**
     * Protected constructer initializes the three arrays that store funcitons provided in OOWriter,
     * their keyboard shortcuts and few most obvious keywords for each shortcut at a search
     */
    DataManager(){
        initilazeArrays();
        String realPath;
        String tempPath = this.getProtectionDomainPath();/////////////////////////////////////////.
               tempPath = tempPath.substring(0, tempPath.length() - 1);/////////////////////////////
               tempPath = tempPath.substring(0, tempPath.lastIndexOf('/') + 1);/////////////////////
               realPath = new File(tempPath).getAbsolutePath() + "/";//////////////////////////////
        setHomePath(realPath);////////////////////////////////////////////////////////////////////
    }

    /**
     * initializes the three arrays that store funcitons provided in OOWriter, their keyboard shortcuts
     * and few most obvious keywords for each shortcut at a search
     */
    private void initilazeArrays() {//43
        relatedWords = new String[][]{{"calculation","formula","bar","equation","insert"},
                                      {"insert","fields","current","curser","position"},
                                      {"autotext","complete","incorrect","spelling","missing"},
                                      {"autotext","edit","change","substitute","spelling"},
                                      {"data source","template","view","address book","fields"},
                                      {"frame","box","square"},
                                      {"Navigate","on","off","jump"},
                                      {"Navigate","Page","jump"},
                                      {"spellings","spell","correct","check","grammar","language"},
                                      {"Thesaurus","dictionary","language"},
                                      {"extension", "mode","expand","crop"},
                                      {"field","shading","on","off"},
                                      {"multiple", "selection","additional","select"},
                                      {"block","select","selection","text"},
                                      {"update","input","fields","field","add","adding"},
                                      {"can't","cannot","print","not printable","unable","not"},
                                      {"style","styles","format","formatting"},
                                      {"style","styles","custom","look","appearance"},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},
                                      {},            
        };
        
        functionNames = new String[]{"Fomula Bar","Insert Fields","Complete AutoText","Edit AutoText","Open Data Source View",
        "To select next frame","To On/Off Navigator","Navigator on, go to page number","Perform spellcheck","To access Thesaurus","Extension mode",
        "To on/off Field shadings","Additional slection mode","Block selection mode","Update Input Fields and Input Lists",
        "To on/off nonprinting characters","Styles and Formatting window on/off","Create Style","Sets focus to Apply Style box",
        "Update Style","Numbering on","Insert or edit Table","Bullets on","Numbering / Bullets off","Select All","Justify",
        "Double Underline","Centered","Find and Replace","Superscript","Align Left","Align Right","Subscript","Redo last action",
        "Apply Default paragraph style","Apply Heading 1 paragraph style","Apply Heading 2 paragraph style",
        "Apply Heading 3 paragraph style","1.5 Line Spacing","Calculates the selected text and copies the result to the clipboard",
        "Custom hyphens; hyphenation set by you","Non-breaking dash (is not used for hyphenation)","Run macro field"};

        shortcuts = new String[]{"F2","Ctrl+F2","F3","Ctrl+F3","F4","Shift+F4","F5","Ctrl+Shift+F5","F7","Ctrl+F7","F8","Ctrl+F8",
        "Shift+F8","Ctrl+Shift+F8","F9","Ctrl+F9","Shift+F9","Ctrl+Shift+F9","Ctrl+F10","F11","Shift+F11","Ctrl+F11",
        "Ctrl+Shift+F11","F12","Ctrl+F12","Shift+F12","Ctrl+Shift+F12","Ctrl+A","Ctrl+J","Ctrl+D","Ctrl+E","Ctrl+F",
        "Ctrl+Shift+P","Ctrl+L","Ctrl+R","Ctrl+Shift+B","Ctrl+Y","Ctrl+0 (zero)","Ctrl+1","Ctrl+2","Ctrl+3","Ctrl+5",
        "Ctrl+ Plus Key(+)","Ctrl+Hyphen(-)","Ctrl+Shift+minus sign (-)","Ctrl+multiplication sign * (only on number pad)"};
    }

    /**
     * reapeatedly call 'displayIfVisible' method
     *
     * @param rInterface The interface on which the shortcuts are supposed to display
     */
    void displayShortcuts(ReminderInterface rInterface) {
        int leng = functionNames.length;
        while(1>0){
            displayIfVisible(leng,rInterface);
        }
    }

    /**
     * Extract functions that well matched and slightly matched to the given discription and do further comparing
     * on slightly matched keywords with more related key words
     *
     * @param stringToSearch The description of the function entered by theh user
     * @return The set of fucntions that are matching to the description by user, and their keyboard shortcuts
     */
    String findRealatedShortcuts(String stringToSearch) {
        String searchResult = "";
        String oneWordMatched = "";
        int index = 0;
        int ind = 0;

        int i = 0;
        while(i<relatedWords.length){
            String arr[] = relatedWords[i];
            int j = 0;
            int flag = 0;

            while(j<arr.length && flag <2 ){
                if (isMatching(stringToSearch,arr[j])){
                    flag++;
                    System.out.println(flag);
                }
                j++;
            }
            if (flag == 2){
                searchResult = searchResult + functionNames[i]+" \t "+shortcuts[i]+":";
                index++;
            }else if (flag == 1){
                oneWordMatched = oneWordMatched+""+i+" ";
                ind++;
                System.out.println("there.. added to char string "+ i);
            }
            i++;
        }
        if(ind!=0){
            StringTokenizer st;
            st = new StringTokenizer(oneWordMatched, " ");
            int []lineNumbers = new int[st.countTokens()];
            int arrindex = 0;
            while(st.hasMoreTokens()){
                lineNumbers[arrindex] = Integer.parseInt(st.nextToken());
            }

            String lines[] = readFromFiles(lineNumbers);
            int k = 0;
            while(k<lines.length){
                if(isWordMatching(stringToSearch,lines[k])){
                    searchResult = searchResult + functionNames[lineNumbers[k]]+" \t "+shortcuts[lineNumbers[k]]+":";
                    System.out.println("searchResult" + searchResult);
                }
                k++;
            }
        }
        System.out.println(searchResult);
        return searchResult;
    }

    /**
     * If reminder interface is visible display functions and their shortcuts repetitively one by one
     *
     * @param leng The total number of functions that are supposed to dispaly on reminder interface
     * @param rInterface The interface on which the shortcuts are supposed to display
     */
    private void displayIfVisible(int leng, ReminderInterface rInterface) {
        String nextshortcutname;
        String nextshortcut;
        while (leng>0 ){
            nextshortcutname = functionNames[leng-1];
            nextshortcut = shortcuts[leng-1];
            leng--;
            rInterface.refresh(nextshortcutname,nextshortcut);
            try {
                Thread.sleep(10000);
            } catch (InterruptedException ex) {
                Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * Extracts the lines containig relavent keywords for each slightly matched function
     *
     * @param oneWordMatched The set of methods that slightly matched to the user entered description
     * @return A set of extra keywords to match against the given description, as a String
     */
    private String[] readFromFiles(int[] oneWordMatched) {
        String string[] = new String[oneWordMatched.length];
        int index = 0;
        int count = 0;
        File file = null;
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        DataInputStream dis = null;

        String filname = homepath + "/help/RelatedWords.txt";///////////////////////////////////////////
        file = new File("C:/Users/Deranga/Documents/NetBeansProjects/FinalProject/ShortcutReminder/src/RelatedWords.txt");//C:/Users/Deranga/Documents/NetBeansProjects/FinalProject/ShortcutReminder/src/RelatedWords.txt
            try{
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                dis = new DataInputStream(bis);

                while(index<oneWordMatched.length){
                    String line = dis.readLine();
                    System.out.println("line read "+line);
                    System.out.println("ggggggggggg "+oneWordMatched[index]+"count"+count);
                    System.out.println(count == oneWordMatched[index]);

                    if(count == oneWordMatched[index]){
                        string[index] = line;
                        index++;
                    }
                    count++;
                }
                fis.close();
                bis.close();
                dis.close();

            }catch(FileNotFoundException e){
                e.printStackTrace();
            }catch(IOException e){
                e.printStackTrace();
            }
        return string;
    }

    /**
     * Compares each most obvious keyword against the description of user
     *
     * @param wordToSearch The description entered by the user
     * @param string The keyword to match against the description of user
     * @return If description matches the keyword return 'true' or 'false' otherwise
     */
    private boolean isMatching(String wordToSearch, String string) {
        StringTokenizer st;
        st = new StringTokenizer(wordToSearch, " ");
        while(st.hasMoreElements()){
            if(st.nextToken().equalsIgnoreCase(string)){
                return true;
            }
        }
        return false;
    }

    /**
     * Further compares the user entered description against the keywords that slightly matched to any one of
     * the set of most obvious keywords
     *
     * @param stringToSearch The description entered by the user
     * @param string The keyword to match against the description of user
     * @return If description matches any one of the given set of keywords return 'true' or 'false' otherwise
     */
    private boolean isWordMatching(String stringToSearch, String string) {
        StringTokenizer st,str;
        st = new StringTokenizer(stringToSearch, " ");
        str = new StringTokenizer(string, " ");

        String[] searchFor = new String[st.countTokens()];
        String[] searchIn = new String[str.countTokens()];
        int k = 0;
        while(st.hasMoreTokens()){
                searchFor[k] = st.nextToken();
                System.out.println(searchFor[k]);
                k++;
        }
        k=0;
        while(str.hasMoreTokens()){
                searchIn[k] = str.nextToken();
                System.out.println(searchIn[k]);
                k++;
        }

        int i = 0;
        int j = 0;
        while(i<searchFor.length){
            j=0;
            while(j<searchIn.length){
                System.out.println("comparing"+searchFor[i]+"with"+searchIn[j]);
                if (searchFor[i].compareToIgnoreCase(searchIn[j])==0){
                    System.out.println("exited here");
                    return true;
                }
                j++;
            }
            i++;
        }

        System.out.println("exited there");
        return false;
    }

    private String getProtectionDomainPath() {////////////////////////////////////////////////////////
        String path;
        try {
            path = DataManager.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
        } catch (URISyntaxException ex) {
            Logger.getLogger(DataManager.class.getName()).log(Level.SEVERE, null, ex);
            path = DataManager.class.getProtectionDomain().getCodeSource().getLocation().getPath().replace("%20", "");
        }
        return path;
    }

    private void setHomePath(String homePath) {/////////////////////////////////////////////////////////
        assert(this.homepath==null);
        this.homepath = homePath;
    }



}
















/*
        "Non-breaking spaces. Non-breaking spaces are not used for hyphenation and are not expanded if the text is justified",
        "Line break without paragraph change","Manual page break","Column break in multicolumnar texts",
        "Inserting a new paragraph without numbering","Inserting a new paragraph directly before or after a section or a table",
        "Move cursor to left","Move cursor with selection to the left","Go to beginning of word","Selecting to the left word by word",
        "Move cursor to right","Move cursor with selection to the right","Go to start of next word","Selecting to the right word by word",
        "Move cursor up one line","Selecting lines in an upwards direction","Move cursor to beginning of the previous paragraph",
        "Select to beginning of paragraph. Next keystroke extends selection to beginning of previous paragraph","Move cursor down one line",
        "Selecting lines in a downward direction","Move cursor to beginning of next paragraph",
        "Select to end of paragraph. Next keystroke extends selection to end of next paragraph","Go to beginning of line",
        "Go and select to the beginning of a line","Go to end of line","Go and select to end of line","Go to start of document",
        "Go and select text to start of document","Go to end of document","Go and select text to end of document",
        "Switch cursor between text and header","Switch cursor between text and footer","Insert mode on/off","Screen page up",
        "Move up screen page with selection","Move down screen page","Move down screen page with selection","Delete text to end of word",
        "Delete text to beginning of word in a list: delete an empty paragraph in front of the current paragraph",
        "Delete text to end of sentence","Delete text to beginning of sentence","Next suggestion with Automatic Word Completion",
        "Use previous suggestion with Automatic Word Completion",
        "Use this combination to quickly dock or undock the Navigator, Styles and Formatting window, or other windows",
        "Move the active paragraph or selected paragraphs up one paragraph",
        "Move the active paragraph or selected paragraphs down one paragraph",
        "The heading in format 'Heading X' (X = 1-9) is moved down one level in the outline",
        "The heading in format 'Heading X' (X = 2-10) is moved up one level in the outline",
        "At the start of a heading: Inserts a tab stop. Depending on the Window Manager in use, Alt+Tab may be used instead.To " +
                "change the heading level with the keyboard, first position the cursor in front of the heading",
        "If the active cell is empty: selects the whole table. Otherwise: selects the contents of the active cell. Pressing" +
                " again selects the entire table",
        "If the active cell is empty: goes to the beginning of the table. Otherwise: first press goes to beginning of the active" +
                " cell, second press goes to beginning of the current table, third press goes to beginning of document",
        "If the active cell is empty: goes to the end of the table. Otherwise: first press goes to the end of the active cell, second " +
                "press goes to the end of the current table, third press goes to the end of the document",
        "Inserts a tab stop (only in tables). Depending on the Window Manager in use, Alt+Tab may be used instead",
        "Increases/decreases the size of the column/row on the right/bottom cell edge",
        "Increase/decrease the size of the column/row on the left/top cell edge","Like Alt, but only the active cell is modified",
        "Like Alt, but only the active cell is modified","3 seconds in Insert mode, Arrow Key inserts row/column, Ctrl+Arrow Key inserts cell",
        "3 seconds in Delete mode, Arrow key deletes row/column, Ctrl+Arrow key merges cell with neighboring cell",
        "Removes cell protection from all selected tables. If no table is selected, then cell protection is removed from all of the " +
                "tables in the document",
        "If no whole cell is selected, the text from the cursor to the end of the current sentence is deleted. If the cursor is at the end" +
                " of a cell, and no whole cell is selected, the contents of the next cell are deleted. If no whole cell is selected and " +
                "the cursor is at the end of the table, the following sentence from below the table will be deleted and the remainder of " +
                "that paragraph will be moved into the last table cell. If an empty line follows the table, the empty line will be deleted." +
                " If one or more cells are selected, the whole rows containing the selection will be deleted. If all rows are selected " +
                "completely or partially, the entire table will be deleted.","Cursor is inside a text frame and no text is selected: " +
                "Escape selects the text frame. Text frame is selected: Escape clears the cursor from the text frame",
        "If a text frame is selected: positions the cursor to the end of the text in the text frame. If you press any key that produces a " +
                "character on screen, and the document is in edit mode, the character is appended to the text","Move object",
        "Resizes by moving lower right corner","Resizes by moving top left corner","Selects the anchor of an object (in Edit Points mode)"
 */



//FUNCTION NAMES

/*
 "Select next frame","Navigator On/Off","Navigator on, go to page number","Spellcheck","Thesaurus","Extension mode",
        "Field shadings on/off","Additional slection mode","Block selection mode","Update Input Fields and Input Lists",
        "Nonprinting vharacters on/off","Styles and Formatting window on/off","Create Style","Sets focus to Apply Style box",
        "Update Style","Numbering on","Insert or edit Table","Bullets on","Numbering / Bullets off","Select All","Justify",
        "Double Underline","Centered","Find and Replace","Superscript","Align Left","Align Right","Subscript","Redo last action",
        "Apply Default paragraph style","Apply Heading 1 paragraph style","Apply Heading 2 paragraph style","Apply Heading 3 paragraph style",
        "1.5 Line Spacing","Calculates the selected text and copies the result to the clipboard","Custom hyphens; hyphenation set by you",
        "Non-breaking dash (is not used for hyphenation)","Run macro field"

 */



//SHORTCUTS

/*
 ,"Shift+F4","F5","Ctrl+Shift+F5","F7","Ctrl+F7","F8","Ctrl+F8",
        "Shift+F8","Ctrl+Shift+F8","F9","Ctrl+F9","Shift+F9","Ctrl+Shift+F9","Ctrl+F10","F11","Shift+F11","Ctrl+F11",
        "Ctrl+Shift+F11","F12","Ctrl+F12","Shift+F12","Ctrl+Shift+F12","Ctrl+A","Ctrl+J","Ctrl+D","Ctrl+E","Ctrl+F",
        "Ctrl+Shift+P","Ctrl+L","Ctrl+R","Ctrl+Shift+B","Ctrl+Y","Ctrl+0 (zero)","Ctrl+1","Ctrl+2","Ctrl+3","Ctrl+5",
        "Ctrl+ Plus Key(+)","Ctrl+Hyphen(-)","Ctrl+Shift+minus sign (-)","Ctrl+multiplication sign * (only on number pad)"
 */